/*
 * CTcpMediaCaster.h
 *
 *  Created on: 2016年5月13日
 *      Author: terry
 */

#ifndef CTCPMEDIACASTER_H_
#define CTCPMEDIACASTER_H_

#include "RtpMediaCaster.h"
#include "TThread.h"
#include "TEvent.h"
#include "TCriticalSection.h"
#include <deque>
#include "RtpPackager.h"
#include "Socket.h"
#include "TByteBuffer.h"
#include "NetAddress.h"
#include "MediaPacketQueue.h"
#include "TcpClient.h"


namespace av
{

typedef std::shared_ptr< RtpPackager >		RtpPackagerPtr;
typedef std::deque< NetAddress >        RtpTargetArray;
typedef std::shared_ptr< TcpClient >	TcpClientPtr;
typedef std::deque< TcpClientPtr >		TcpClientArray;


class CTcpMediaCaster: public RtpMediaCaster, public comn::Thread , public RtpPackagerSink
{
public:
	CTcpMediaCaster();
	virtual ~CTcpMediaCaster();

	virtual int open(const std::string& ip, uint16_t port, int codec, int clockRate, int payload, int ssrc);

	virtual void close();

	virtual bool isOpen();

	virtual void setID(int id);

	virtual int getID();

	virtual bool addTarget(const std::string& ip, uint16_t port);

	virtual void removeTarget(const std::string& ip, uint16_t port);

	virtual size_t getTargetCount();

	virtual void removeAllTarget();


    virtual void onMediaFormat(const MediaFormat& fmt);

    virtual void onMediaPacket(MediaPacketPtr& pkt);

    virtual void onMediaEvent(int event);

protected:
	virtual int run();
	virtual void doStop();

	virtual void onSlicePacket(const RtpPacket& pkt);

protected:
	RtpPackager* createPackager(int codec);
	void clearCache();

	void sendPacket(MediaPacketPtr& pkt);
	void assemble(const RtpPacket& pkt);

	void sendBuffer(ByteBufferPtr& buffer);

protected:

	NetAddress	m_addr;
	MediaPacketQueue    m_pktQueue;

	RtpTargetArray	m_targets;
	comn::CriticalSection	m_cs;

	int64_t 	m_packetCount;
	uint32_t    m_lastTime;

	RtpPackagerPtr	m_packager;

	uint16_t    m_seq;
	uint32_t    m_ssrc;
	uint8_t 	m_payload;

	uint32_t    m_initTime;
	int	m_id;

	TcpClientArray	m_tcpClients;
	ByteBufferPtr	m_buffer;

};




} /* namespace av */

#endif /* CTCPMEDIACASTER_H_ */
